/**
 * @author: yd
 * @recentUpdate: 2020-05-20
 * @Time: 15:07
 * @CopyRight sr  All rights reserved
 * @Notice: 该文件统一处理参数可能出现的错误，如在此文件做任何改动请详细写明目的(注释),否则出现问题后果自负
 */
const common = require('lib/utils/common.js');

module.exports = (options = {}) => {
  return async (ctx, next) => {
    /**
     * @param requiredParams: String(单个), Array(多个), Object: label为字段名称, value为提示语
     */
    ctx.requiredParams = (requiredParams) => {
      let method = ctx.method;
      let params  = method.toLocaleUpperCase() === 'GET' ? ctx.query : ctx.request.body;
      if(!common.YD_isEmpty(requiredParams)) {
        if(typeof requiredParams === 'string') {
          if(!(requiredParams in params) || (!params[requiredParams] && params[requiredParams] !== 0)) {
            ctx.fail('字段' + requiredParams +'为必填');
            return true;
          }
        }
        if(Array.isArray(requiredParams)) {
          let paramsKeys = Object.keys(params);
          for(let i = 0;i<requiredParams.length;i++) {
            if(!paramsKeys.includes(requiredParams[i]) || (!params[requiredParams[i]] && params[requiredParams[i]] !== 0)) {
              ctx.fail('字段' + requiredParams[i] +'为必填');
              return true;
              break;
            }
          }
        }
        if(Object.prototype.toString.call(requiredParams) === '[object Object]') {
          for(let key in requiredParams) {
            if(!(key in params) || (!params[key] && params[key] !== 0)) {
              if(requiredParams[key]) {
                ctx.fail(requiredParams[key]);
              }else {
                ctx.fail('字段' + key +'为必填');
              }
              return true;
              break;
            }
          }

        }
      }
    };
    await next();
  }
};
